<?php

/// +----------------------------------------------------------------------
// | 短信
// +----------------------------------------------------------------------
// | Author: lcx <916450508@qq.com >
// +----------------------------------------------------------------------
// | Date: 2018/12/5
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\common\controller\AdminController;
use think\Db;
use think\facade\Cache;
use tool\Curl;
use app\common\model\SmsNameListModel;
use app\common\model\ApplicationsModel;
use app\common\model\SmsSendRecordModel;

class Sms extends AdminController
{

    protected $curl;
    protected $smsNameListModel;
    protected $smsSendRecordModel;
    protected $applicationsModel;

    /**
     * 初始化
     * node constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->curl = new Curl();
        $this->smsNameListModel = new SmsNameListModel();  // 短信模型
        $this->smsSendRecordModel = new SmsSendRecordModel();  // 短信发送记录模型
        $this->applicationsModel = new ApplicationsModel();
    }

    /**
     * 短信列表
     */
    public function index()
    {
        // ajax访问
        if ($this->request->get('type') == 'ajax') {
            // 接收参数
            $page = $this->request->get('page', 1);
            $limit = $this->request->get('limit', 10);
            $select = (array)$this->request->get('select', []);

            $where=[];
            // 搜索条件
            foreach ($select as $k => $v)
            {
                if ($k == 'phone' && $v != '') {
                    $where[] = [$k, 'LIKE', '%' . $v . '%'];
                }
            }
            $field = '*';
            $order = 'id DESC';
            // 列表查询
            $data = $this->smsNameListModel->getAll($where, $field, $page, $limit,[], $order);
            // 数量查询
            $count = $this->smsNameListModel->getCount($where);
            // 数据组装
            $info = [
                'limit'        => $limit,
                'page_current' => $page,
                'page_sum'     => ceil($count / $limit),
            ];
            $msg = '暂无数据！';
            if ($data) {
                $msg = '查询成功！';
                foreach ($data as $k => &$v)
                {
                    $v['type_name'] = config('admin.sms_type')[$v['type']];
                    $v['create_time'] = !empty($v['create_time'])?dateTime($v['create_time']):'';
                }
            }
            $list = [
                'code'  => 0,
                'msg'   => $msg,
                'count' => $count,
                'info'  => $info,
                'data'  => $data,
            ];
            return json($list);
        }

        // 基础数据
        $basic_data = [
            'title' => '短信列表',
            'data'  => '',
        ];

        return $this->fetch('', $basic_data);
    }

    /**
     * 新增短信
     * @return mixed
     */
    public function add()
    {
        // 渲染添加页面
        if (!$this->request->isPost()) {
            //基础数据
            $basic_data = [
                'type' => config('admin.sms_type'),
            ];
            $this->assign($basic_data);
            return $this->fetch();
        }
        // 处理添加操作
        else {
            // 接收参数
            $post = $this->request->post();
            if(!empty($post['phone']) && !isMobile($post['phone'])){
                return json(['code' => 0, 'msg' => '手机号码不合法']);
            }
            // 详情数据
            $data=$post;
            $data['create_time'] = time();

            // 开启事务
            Db::startTrans();
            try{
                // 1-- 添加短信
                $res = $this->smsNameListModel->add($data);
                // 事务提交
                Db::commit();
            } catch (\Exception $e) {
                // 事务回滚
                Db::rollback();
                $res = false;
            }

            if ($res) {
                return json(['code' => 1, 'msg' => '添加成功']);
            }
            return json(['code' => 0, 'msg' => '添加失败']);
        }
    }

    // 编辑短信
    public function edit()
    { // 渲染编辑页面
        if (!$this->request->isPost()) {
            // 接收参数
            $id = $this->request->get('id');

            // 获取短信信息
            $data = $this->smsNameListModel->getOne(['id'=>$id]);

            if (empty($data)) return msg_error('暂无数据，请重新刷新页面！');
            $data['create_time']=!empty($data['create_time'])?dateTime($data['create_time']):'';
            // 基础数据
            $basic_data = [
                'type' => config('admin.sms_type'),
                'data'  => $data,
            ];
            $this->assign($basic_data);
            return $this->fetch('add');
        }
        // 处理编辑操作
        else {
            // 接收参数
            $post = $this->request->post();
            //清空菜单缓存
            clear_menu();

            $where['id'] = $post['id'];
            if(!empty($post['phone']) && !isMobile($post['phone'])){
                return json(['code' => 0, 'msg' => '手机号码不合法']);
            }
            // 开启事务
            Db::startTrans();
            try{
                // 1-- 修改短信
                $res=$this->smsNameListModel->edit($where, $post);
                unset($where);
                // 事务提交
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
            }
            if ($res) {
                return json(['code' => 1, 'msg' => '编辑成功']);
            }
            return json(['code' => 0, 'msg' => '编辑失败']);
        }
    }


    /**
     * 短信发送记录列表
     */
    public function record()
    {
        // ajax访问
        if ($this->request->get('type') == 'ajax') {
            // 接收参数
            $page = $this->request->get('page', 1);
            $limit = $this->request->get('limit', 10);
            $select = (array)$this->request->get('select', []);

            $where=[];
            // 搜索条件
            foreach ($select as $k => $v)
            {
                if ($k == 'key' && $v != '') {
                    $where[] = ['phone|app_sn|platform_account|platform_source', 'LIKE', '%' . $v . '%'];
                }
            }

            $field = '*';
            $order = 'id DESC';
            // 列表查询
            $data = $this->smsSendRecordModel->getAll($where, $field, $page, $limit,[], $order);
            // 数量查询
            $count = $this->smsSendRecordModel->getCount($where);
            // 数据组装
            $info = [
                'limit'        => $limit,
                'page_current' => $page,
                'page_sum'     => ceil($count / $limit),
            ];
            $msg = '暂无数据！';
            if ($data) {
                $msg = '查询成功！';
                foreach ($data as $k => &$v)
                {
                    $v['create_time'] = dateTime($v['create_time']);
                }
            }
            $list = [
                'code'  => 0,
                'msg'   => $msg,
                'count' => $count,
                'info'  => $info,
                'data'  => $data,
            ];
            return json($list);
        }

        // 基础数据
        $basic_data = [
            'title' => '短信记录列表',
            'data'  => '',
        ];

        return $this->fetch('', $basic_data);
    }



}
